package cn.wolfcode.trip.app.controller;

import cn.wolfcode.trip.base.domain.User;
import cn.wolfcode.trip.base.query.TravelQuery;
import cn.wolfcode.trip.base.service.ITravelService;
import cn.wolfcode.trip.base.service.IUserService;
import cn.wolfcode.trip.base.util.JSONResult;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * Created by 13925 on 2018/10/28.
 */
/*
    用户的控制层
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private IUserService userService;


    @Autowired

    private ITravelService travelService;

    /**
     * 用户注册
     *
     * @param user 页面上传入的用户信息
     * @return
     */
    @PostMapping
    public JSONResult register(User user) {
        JSONResult result = new JSONResult();
        //检查邮箱是否存在,如果传入密码,表示登录查询
        User temp = userService.getUserByEmailAndPassword(user.getEmail(), null);
        //判断邮箱是否重复(可用)
        if (temp != null) {
            //邮箱已经被用调用mark方法发送异常信息
            result.mark("邮箱已被使用");
        } else {
            //设置默认头像和背景墙
            user.setHeadImgUrl("/img/user/head.jpg");
            user.setCoverImgUrl("/img/user/bg.jpeg");
            //将用户信息保存至数据库
            userService.save(user);
        }
        return result;
    }

    @PutMapping
    public JSONResult update(User user) {
        JSONResult result = new JSONResult();
        try {
            userService.update(user);
            //目的:用于同步更新页面缓存数据
            result.setResult(user);
        } catch (Exception e) {
            result.mark(e.getMessage());
        }
        return result;
    }

    @GetMapping("/{authorId}/travels")
    public PageInfo listTravelByUserId(TravelQuery qo) {
        return travelService.query(qo);

    }


}
